package com.baizhi.luceneindex.impl;

import com.baizhi.dao.CmfzArticleMapper;
import com.baizhi.entity.CmfzArticle;
import com.baizhi.luceneindex.LuceneService;
import com.baizhi.utils.LuceneUtil;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class LuceneServiceImpl implements LuceneService {
    @Autowired
    private CmfzArticleMapper cmfzArticleMapper;
    /**
     * 1.添加一个
     */
    @Override
    public boolean addCmfzArticle(CmfzArticle cmfzArticle) {
//        数据封装到document中
        Document document = new Document();
//        获取一个索引写出对象
        IndexWriter indexWriter = LuceneUtil.getIndexWriter();
//        创建索引 数据给所索引写出对象 并且写在索引库
        try {
            indexWriter.addDocument(document);
            //        释放资源
            LuceneUtil.indexCommit(indexWriter);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            //        释放资源
            LuceneUtil.indexCommit(indexWriter);
            return false;
        }
    }

    /**
     * 添加多个
     * @param cmfzArticles
     * @return
     */
    @Override
    public boolean addCmfzArticles(List<CmfzArticle> cmfzArticles) {
        ArrayList<Document> documents=new ArrayList<>();
        for (CmfzArticle cmfzArticle : cmfzArticles) {
            Document document=new Document();
            document.add(new StringField("articleId",cmfzArticle.getArticleId().toString(), Field.Store.YES));
            document.add(new TextField("articleName",cmfzArticle.getArticleName(), Field.Store.YES));
            document.add(new TextField("articleContent",cmfzArticle.getArticleContent(), Field.Store.YES));

            documents.add(document);
        }
//        获取一个索引写出对象
        IndexWriter indexWriter = LuceneUtil.getIndexWriter();
//        创建索引  获取数据给索引写出对象  并把对象写入索引库
        try {
            indexWriter.addDocuments(documents);
            //        释放资源
            LuceneUtil.indexCommit(indexWriter);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            //        释放资源
            LuceneUtil.indexCommit(indexWriter);
            return false;
        }

    }

    /**
     * 根据关键词全文检索上师文章
     * @param page
     * @param rows
     * @param keyword
     * @return
     */
    @Override
    public Map queryByKeyWord(int page,int rows,String keyword) {
        Map map=new HashMap();
        List<CmfzArticle> cmfzArticleList=new ArrayList<>();
//         1. 准备搜索词 处理搜索词
        Query query = LuceneUtil.getQuery(keyword);

//    2.准备好的搜索对象
        IndexSearcher indexSearcher = LuceneUtil.getIndexSearcher();

        QueryScorer queryScorer = new QueryScorer(query);
        SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<font color='red'>", "</font>");
        Highlighter highlighter = new Highlighter(formatter, queryScorer);
//    3.搜索 得到位置信息
        TopDocs topDocs = null;
        try {
            topDocs = indexSearcher.search(query, 100);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        map.put("total",scoreDocs.length);
        for (int i = 0; i < scoreDocs.length; i++) {
//            搜索对象的分值
            float score = scoreDocs[i].score;

            int doc = scoreDocs[i].doc;
            Document document = null;
            try {
                document = indexSearcher.doc(doc);
            } catch (IOException e) {
                e.printStackTrace();
            }

            String articleId=document.get("articleId");
            int id=Integer.parseInt(articleId);
            String articleName=document.get("articleName");
            String articleContent=document.get("articleContent");
            //      2.使用高亮器处理搜索结果
            /**
                   * 三个参数 1.分词器 2.要高亮的属性名 3.从document中获取到的文本数据(搜索结果)
              */
            String articleName1 = null;
            try {
                articleName1 = highlighter.getBestFragment(LuceneUtil.analyzer,"articleName", articleName);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InvalidTokenOffsetsException e) {
                e.printStackTrace();
            }
            String articleContent1 = null;
            try {
                articleContent1 = highlighter.getBestFragment(LuceneUtil.analyzer,"articleContent", articleContent);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InvalidTokenOffsetsException e) {
                e.printStackTrace();
            }

            CmfzArticle cmfzArticle=new CmfzArticle();
            cmfzArticle.setArticleId(id);
            cmfzArticle.setArticleName(articleName1);
            cmfzArticle.setArticleContent(articleContent1);
            cmfzArticleList.add(cmfzArticle);
        }
        map.put("rows",cmfzArticleList);
        return map;
    }

    /**
     * 删除所有
     * @return
     */
    @Override
    public boolean deleteAll() {
        IndexWriter indexWriter = LuceneUtil.getIndexWriter();
        try {
            indexWriter.deleteAll();
            LuceneUtil.indexCommit(indexWriter);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            LuceneUtil.indexCommit(indexWriter);
            return false;
        }

    }

    /**
     * 根据ID删除
     * @param id
     * @return
     */
    @Override
    public boolean deleteById(int id) {
        String articleId = String.valueOf(id);
        IndexWriter indexWriter=LuceneUtil.getIndexWriter();
        try {
            indexWriter.deleteDocuments(new Term("articleId",articleId));
            LuceneUtil.indexCommit(indexWriter);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            LuceneUtil.indexCommit(indexWriter);
            return false;
        }
    }

    /**
     * 根据ID修改
     * @param cmfzArticle
     * @return
     */
    @Override
    public boolean updateCmfzArticleById(CmfzArticle cmfzArticle) {
        Document document = new Document();
        String articleId = cmfzArticle.getArticleId().toString();
        document.add(new StringField("articleId",articleId, Field.Store.YES));
        document.add(new TextField("articleName",cmfzArticle.getArticleName(), Field.Store.YES));
        document.add(new TextField("articleContent",cmfzArticle.getArticleContent(), Field.Store.YES));


        IndexWriter indexWriter = LuceneUtil.getIndexWriter();
        try {
            indexWriter.updateDocument(new Term("articleId",articleId),document);
            LuceneUtil.indexCommit(indexWriter);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            LuceneUtil.indexCommit(indexWriter);
            return false;
        }
    }

    /**
     * 重置  先删除所有，在添加所有
     * @return
     */
    @Override
    public Map resetIndex() {
        Map map=new HashMap();
        IndexWriter indexWriter = LuceneUtil.getIndexWriter();
        try {
            indexWriter.deleteAll();
        } catch (IOException e) {
            e.printStackTrace();
        }

//        1.准备数据
        List<CmfzArticle> cmfzArticleList=cmfzArticleMapper.getAllArticle();
        ArrayList<Document> documents=new ArrayList<>();

//        2.把数据封装到document中
        for (CmfzArticle cmfzArticle : cmfzArticleList) {
            Document document=new Document();
            document.add(new StringField("articleId",cmfzArticle.getArticleId().toString(), Field.Store.YES));
            document.add(new TextField("articleName",cmfzArticle.getArticleName(), Field.Store.YES));
            document.add(new TextField("articleContent",cmfzArticle.getArticleContent(), Field.Store.YES));

            documents.add(document);
        }

//        4.创建索引  数据给索引写出对象 并把数据写到索引库中
        try {
            indexWriter.addDocuments(documents);
            //        5.释放资源
            LuceneUtil.indexCommit(indexWriter);
            map.put("isReset",true);

        } catch (IOException e) {
            e.printStackTrace();
            //        5.释放资源
            LuceneUtil.indexCommit(indexWriter);
            map.put("isReset",false);
        }
        return map;
    }
}
